
const loginContainer = document.getElementsByClassName("login-container")[0];
const register = document.getElementById("register");
console.log(register)
const alerts = document.getElementsByClassName("alerts")[0];
console.log(alerts);
const navRight = document.getElementsByClassName("nav-right")[0];
const emailRegex = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/;
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,64}$/;
//显示错误信息
function showError(errorElement) {
    errorElement.style.display = 'block';
    setTimeout(() => {
        errorElement.style.opacity = '1';
        errorElement.style.visibility = 'visible';
    }, 5);
}

//隐藏错误信息
function hideError(errorElement) {
    errorElement.style.opacity = '0';
    errorElement.style.visibility = 'hidden';
    setTimeout(() => {
        errorElement.style.display = 'none';
    }, 120);
}

// 警告框
function signalert(alert, message, color) {
    if (alert) {
        alert.style.display = 'block';
        alert.innerHTML = message;
        alert.style.color = color;
        setTimeout(function () {
            alert.style.display = 'none';
        }, 2000); //两秒后警告框消失
    }
}
// signalert();
// 输入验证函数
function validateEmail(input) {
    return emailRegex.test(input.value);
}

function validatePassword(input) {
    return input.value !== '';
}

function validatePasswordFormat(input) {
    return passwordRegex.test(input.value);
}

function validateTerms(termsInput) {
    return termsInput.checked;
}

navRight.onclick = function () {
    location.href = "/user/recommendPage";
}

// 倒计时函数
function startCountdown(button, time, storageKey) {
    let countdownTime = time;
    let timer;

    function tick() {
        if (countdownTime > 0) {
            localStorage.setItem(storageKey, countdownTime);
            button.innerHTML = countdownTime + "秒后重发";
            countdownTime--;
        } else {
            clearInterval(timer);
            localStorage.removeItem(storageKey);
            button.disabled = false;
            button.innerHTML = "发送验证码";
            return;
        }
        timer = setTimeout(tick, 1000);
    }

    // 防止刷新
    let leftTime = parseInt(localStorage.getItem(storageKey)) || 0;
    if (leftTime > 0) {
        countdownTime = leftTime;
        // tick();
        button.disabled = true;
    }


    button.disabled = true;
    // countdownTime = time;
    tick();

}

// 小眼睛点击事件处理
function handleEyeClick(input, eyeclose, eyeopen) {
    if (input.type === 'password') {
        eyeclose.style.display = 'none';
        eyeopen.style.display = 'block';
        input.type = 'text';
    } else {
        eyeclose.style.display = 'block';
        eyeopen.style.display = 'none';
        input.type = 'password';
    }
}

//注册按钮点击事件
register.onclick = function () {
    console.log("1");
    location.href = "http://localhost:8080/user/register";
}


//登录
const loginEmail = document.querySelector("#login-email");
const loginEmailFormat = document.getElementById("login-email-format-Error");
const loginPassword = document.querySelector("#login-password");
const passwordEmpty = document.getElementById("login-passwordEmpty");
const loginCheckbox = document.getElementsByClassName("checkbox")[0];
const loginTerms = document.getElementById("login-terms");
const forgetPassword = document.getElementsByClassName("forget-password")[0];
const loginEyeclose = document.getElementsByClassName("Eyeclose")[0];
const loginEyeopen = document.getElementsByClassName("Eyeopen")[0];
//为各输入框添加监听事件,目的是当输入框中的内容符合要求时,提示语句消失
loginEmail.addEventListener('input', function () {
    if (validateEmail(loginEmail)) {
        hideError(loginEmailFormat);
    } else {
        showError(loginEmailFormat);
    }
});
loginPassword.addEventListener('input', function () {
    if (validatePassword(loginPassword)) {
        hideError(passwordEmpty);
    } else {
        showError(passwordEmpty);
    }
})

document.getElementsByClassName("btn-login")[0].addEventListener('click', event => {
    console.log("登录按钮一点击")
    event.preventDefault();
    // console.log('表单的默认提交行为已被取消');
    // 检查输入内容是否符合要求
    let allValid = true;
    // 检查邮箱格式是否正确
    let isLoginEmailValid = validateEmail(loginEmail);
    if (isLoginEmailValid) {
        // loginEmailFormat.style.display = 'none';
        hideError(loginEmailFormat);
    } else {
        showError(loginEmailFormat);
        allValid = false;
    }

    // 检查密码是否为空
    let isLoginPasswordValid = validatePassword(loginPassword);
    if (isLoginPasswordValid) {
        hideError(passwordEmpty)
    } else {
        showError(passwordEmpty);
        allValid = false;
    }
    // 检查是否同意条款
    let isLoginTermsChecked = validateTerms(loginTerms);

    // 综合判断
    let success1 = isLoginEmailValid && isLoginPasswordValid && !isLoginTermsChecked;
    let success2 = isLoginEmailValid && isLoginPasswordValid && isLoginTermsChecked;
    if (success1 && !success2) {
        console.log("声一响检查未通过");
        loginCheckbox.style.color = 'red';
    } else {
        loginCheckbox.style.color = '';
    }
    if (success2) {
        console.log("所有检查均通过");
        // 如果所有检查都通过，手动提交表单
        document.getElementsByClassName('login-container')[0].submit();

    }
})
document.addEventListener('DOMContentLoaded', function () {
    const alertMessage = document.getElementById('alertMessage');
    if (alertMessage) {
        const messageText = alertMessage.textContent;
        // 根据消息内容判断并设置颜色
        if (messageText.includes('成功')) {
            alertMessage.style.color = 'green';
        } else if (messageText == "该邮箱未被注册" || messageText.includes == "错误" || messageText == "邮箱不存在") {
            alertMessage.style.color = 'red';

        }
        // 设置两秒后消失
        setTimeout(() => {
            alertMessage.style.display = 'none';
        }, 2000);
    }
});




//登录的小眼睛
loginEyeclose.addEventListener('click', () => handleEyeClick(loginPassword, loginEyeclose, loginEyeopen));
loginEyeopen.addEventListener('click', () => handleEyeClick(loginPassword, loginEyeclose, loginEyeopen));

//忘记密码
// 获取内部元素
const forgetPasswordBackground = document.querySelector('.forget-password-background')
const forgetPasswordContainer = document.querySelector('.forget-password-container');
//叉号
const closeBtn = forgetPasswordContainer.querySelector('.icon-quxiao');

//邮箱
const forgetPasswordEmailError = forgetPasswordContainer.querySelector('#forget-password-email-format-Error');
const forgetPasswordEmailFormatText = forgetPasswordContainer.querySelector('.forget-password-email-format-text');
const forgetPasswordEmailInput = forgetPasswordContainer.querySelector('#forget-password-email')
//验证码
const forgetPasswordCodeError = forgetPasswordContainer.querySelector('#forget-password-code-Error');
const forgetPasswordCodeErrorText = forgetPasswordContainer.querySelector('.forget-password-code-Error-text');
const forgetPasswordWriteCode = forgetPasswordContainer.querySelector('#forget-password-code');
const forgetPasswordGetCode = document.getElementById('forget-password-getCode');

//新密码
const forgetPasswordNewpasswordError = forgetPasswordContainer.querySelector('#forget-password-newpassword-Error');
const forgetPasswordErrorText = forgetPasswordContainer.querySelector('.forget-password-Error-text');
const forgetPasswordWritePassword = forgetPasswordContainer.querySelector('#forget-password-newpassword')
//再次输入密码
const forgetPasswordRewpasswordError = forgetPasswordContainer.querySelector('#forget-password-rewpassword-Error');
const forgetPasswordRewpasswordErrorText = forgetPasswordContainer.querySelector('.forget-password-rewpassword-Error-text');
const forgetPasswordWriteRepassword = forgetPasswordContainer.querySelector('#forget-password-rewpassword');
//小眼睛
const forgetPasswordEyeopenFirst = forgetPasswordContainer.querySelectorAll('.icon-eye_open')[0];
const forgetPasswordEyeopenSecond = forgetPasswordContainer.querySelectorAll('.icon-eye_open')[1];
const forgetPasswordEyecloseFirst = forgetPasswordContainer.querySelectorAll('.icon-eye-close')[0];
const forgetPasswordEyecloseSecond = forgetPasswordContainer.querySelectorAll('.icon-eye-close')[1];

//单选框
const forgetPasswordCheckbox = forgetPasswordContainer.querySelector('.checkbox');
const forgetPasswordTerms = forgetPasswordContainer.querySelector('#forget-password-terms');
//确认按钮
const commitChange = forgetPasswordContainer.querySelector('.commit-change');

//大小可以改变的弹窗
function show() {
    forgetPasswordBackground.style.display = "block";
    forgetPasswordContainer.style.display = "flex";
    setTimeout(() => {
        forgetPasswordContainer.style.opacity = 1;
        forgetPasswordContainer.style.transform = "translate(-50%, -50%) scale(1)";
    }, 10);

}

function close() {
    forgetPasswordContainer.style.transform = "translate(-50%, -50%) scale(0)";
    setTimeout(() => {
        forgetPasswordContainer.style.opacity = 0;
        forgetPasswordBackground.style.display = "none";
        forgetPasswordContainer.style.display = "none";
    }, 200);

}

//忘记密码链接点击事件
forgetPassword.addEventListener('click', function (e) {
    // e.preventDefault();
    show()
})
//忘记密码弹窗关闭按钮点击事件
closeBtn.addEventListener('click', function () {
    close()
});
// 添加 input 事件监听器，目的是当输入框中输入东西时，警告语句消失
// 忘记密码邮箱输入事件
forgetPasswordEmailInput.addEventListener('input', function () {
    if (validateEmail(forgetPasswordEmailInput)) {
        hideError(forgetPasswordEmailError);
    }
});

// 忘记密码验证码输入事件
forgetPasswordWriteCode.addEventListener('input', function () {
    if (validatePassword(forgetPasswordWriteCode)) {
        hideError(forgetPasswordCodeError);
    }
});

// 忘记密码新密码输入事件
forgetPasswordWritePassword.addEventListener('input', function () {
    if (validatePasswordFormat(forgetPasswordWritePassword)) {
        hideError(forgetPasswordNewpasswordError);
    }
});

// 忘记密码确认密码输入事件
forgetPasswordWriteRepassword.addEventListener('input', function () {
    if (forgetPasswordWriteRepassword.value === forgetPasswordWritePassword.value) {
        hideError(forgetPasswordRewpasswordError);
    }
});

//发送验证码
// const getCodeButton = document.getElementById('getCode');
forgetPasswordGetCode.addEventListener('click', function () {

    const email = forgetPasswordEmailInput.value;
    if (validateEmail(forgetPasswordEmailInput)) {
        $.ajax({
            url: '/user/sendCodeToForgetPassword',
            type: 'GET',
            data: {
                email: email
            },
            success: function (result) {
                console.log(result)
                const messageText = result.message;
                // 根据消息内容判断并设置颜色
                if (result.code == 200) {
                    signalert(alerts, result.message, "green");
                } else {
                    signalert(alerts, result.message, "red");
                }
            },
            error: function (result) {
                signalert(alerts, result.message, "red");
            }
        });
        startCountdown(forgetPasswordGetCode, 10, 'SecondcountdownTime');

    } else {
        showError(forgetPasswordEmailFormatText);
    }
});
// 为确认按钮添加点击事件
commitChange.onclick = function (event) {
    event.preventDefault();
    // console.log('表单的默认提交行为已被取消');

    // 检查邮箱
    let isEmailValid = validateEmail(forgetPasswordEmailInput);
    if (isEmailValid) {
        hideError(forgetPasswordEmailError);
    } else {
        showError(forgetPasswordEmailError);
    }

    // 检查验证码
    let isCodeValid = validatePassword(forgetPasswordWriteCode);
    if (isCodeValid) {
        hideError(forgetPasswordCodeError);
    } else {
        showError(forgetPasswordCodeError);
    }

    // 检查密码
    let isPasswordValid = validatePasswordFormat(forgetPasswordWritePassword) && validatePassword(forgetPasswordWritePassword);
    if (isPasswordValid) {
        hideError(forgetPasswordNewpasswordError);
    } else {
        showError(forgetPasswordNewpasswordError);
    }

    // 检查确认密码
    let isConfirmPasswordValid = forgetPasswordWriteRepassword.value === forgetPasswordWritePassword.value;
    if (isConfirmPasswordValid) {
        hideError(forgetPasswordRewpasswordError);
    } else {
        showError(forgetPasswordRewpasswordError);
    }

    // 检查是否同意条款
    let isTermsChecked = validateTerms(forgetPasswordTerms);

    // 综合判断
    let success1 = isEmailValid && isCodeValid && isPasswordValid && isConfirmPasswordValid && !isTermsChecked;
    let success2 = isEmailValid && isCodeValid && isPasswordValid && isConfirmPasswordValid && isTermsChecked;
    if (success1) {
        forgetPasswordCheckbox.style.color = 'red';
    } else {
        forgetPasswordCheckbox.style.color = '';
    }

    if (success2) {
        $.ajax({
            type: 'POST',
            url: '/user/forgetPassword',
            data: {
                code: forgetPasswordWriteCode.value,
                email: forgetPasswordEmailInput.value,
                password: forgetPasswordWritePassword.value
            },
            dataType: 'json',
            success: function (response) {
                if (response.code === 200) {
                    signalert(alerts, "密码重置成功", "green");
                    forgetPasswordBackground.style.display = 'none';
                    forgetPasswordContainer.style.display = 'none';
                } else {
                    // 处理失败情况，例如提示错误信息
                    console.log('密码重置失败', response.message);
                    signalert(alerts, response.message, "red");

                }
            },
            error: function (xhr, status, errorThrown) {
                console.log('请求错误', xhr.status, errorThrown);
                // 提示用户请求出错
            }
        });
    }
}
// 忘记密码小眼睛点击事件
forgetPasswordEyecloseFirst.addEventListener('click', () => handleEyeClick(forgetPasswordWritePassword, forgetPasswordEyecloseFirst, forgetPasswordEyeopenFirst));
forgetPasswordEyeopenFirst.addEventListener('click', () => handleEyeClick(forgetPasswordWritePassword, forgetPasswordEyecloseFirst, forgetPasswordEyeopenFirst));
forgetPasswordEyecloseSecond.addEventListener('click', () => handleEyeClick(forgetPasswordWriteRepassword, forgetPasswordEyecloseSecond, forgetPasswordEyeopenSecond));
forgetPasswordEyeopenSecond.addEventListener('click', () => handleEyeClick(forgetPasswordWriteRepassword, forgetPasswordEyecloseSecond, forgetPasswordEyeopenSecond));
